/*
 * Copyright (c) 2006-2019, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-05-24                  the first version
 */

#include <rthw.h>
#include <rtthread.h>
#include "ACM32Fxx_HAL.h"
#include "uart.h"
WDT_HandleTypeDef WDT_Handle;
#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
/*
 * Please modify RT_HEAP_SIZE if you enable RT_USING_HEAP
 * the RT_HEAP_SIZE max value = (sram size - ZI size), 1024 means 1024 bytes
 */
#define RT_HEAP_SIZE (15 * 1024)
static rt_uint8_t rt_heap[RT_HEAP_SIZE];

RT_WEAK void *rt_heap_begin_get(void)
{
    return rt_heap;
}

RT_WEAK void *rt_heap_end_get(void)
{
    return rt_heap + RT_HEAP_SIZE;
}
#endif

void SysTick_Handler(void)
{
    rt_interrupt_enter();

    rt_tick_increase();

    rt_interrupt_leave();
}
void WDT_Init()
{
    uint32_t timer_clk_hz;
    
    WDT_Handle.Instance=WDT;
    WDT_Handle.Init.WDTMode = WDT_MODE_RST;    
    WDT_Handle.Init.WDTDivisor = WDT_DIVISOR_NONE;  //PCLK=64M   
    
    timer_clk_hz = System_Get_APBClock();  
    WDT_Handle.Init.WDTLoad = timer_clk_hz* 5;  
    WDT_Handle.Init.WDTINTCLRTIME = 0xffff;  

    HAL_WDT_Init(&WDT_Handle);  
    HAL_WDT_Start(&WDT_Handle); 
}


/**
 * This function will initial your board.
 */
void rt_hw_board_init(void)
{

    /*
     * TODO 1: OS Tick Configuration
     * Enable the hardware timer and call the rt_os_tick_callback function
     * periodically with the frequency RT_TICK_PER_SECOND.
     */
    System_Init();
    WDT_Init();

    /* Call components board initial (use INIT_BOARD_EXPORT()) */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
    rt_system_heap_init(rt_heap_begin_get(), rt_heap_end_get());
#endif
}

#ifdef RT_USING_CONSOLE

static int uart_init(void)
{
    Uart_Init(115200);
	luart_init(115200);
    return 0;
}
INIT_BOARD_EXPORT(uart_init);

void rt_hw_console_output(const char *str)
{
    rt_size_t i = 0, size = 0;
    char a = '\r';

    size = rt_strlen(str);
    for (i = 0; i < size; i++)
    {
        if (*(str + i) == '\n')
        {
            HAL_LPUART_Send_Bytes(&LPUART_handler, (uint8_t *)&a, 1);
        }
        HAL_LPUART_Send_Bytes(&LPUART_handler, (uint8_t *)(str + i), 1);
    }
}

#endif
